<!-- 表格组件 -->
<template>
  <div class="table_content">
    <!-- 表格 -->
    <div class="table">
      <el-table ref="table"
                :data="tableData"
                v-bind="{...tableConfig}"
                @selection-change="handleSelectionChange"
                style="width: 100%">
        <template v-for="(props, key) in columnData">
          <el-table-column v-if="!props.custom"
                           :key="key"
                           align='center'
                           :type="props.type || 'text'"
                           :width="props.width ? props.width : '120px'"
                           v-bind="{...props}"></el-table-column>
          <!-- 自定义 -->
          <el-table-column v-if="props.custom"
                           :key="key"
                           align='center'
                           :label="props.label"
                           :width="props.width ? props.width : '120px'">
            <template slot-scope="scope">
              <!-- 按钮 -->
              <el-button v-for="(item,idx) in props.group"
                         v-if="props.type == 'btn_group'"
                         :key="idx"
                         :type="item.color"
                         size="mini"
                         @click="btnHandler(scope.row,item)">{{item.name}}</el-button>
              <!-- icon -->
              <img class="table_icon"
                   @click="imgPreview(scope.row[props.prop])"
                   v-if="props.type == 'icon'"
                   :src="scope.row[props.prop]"
                   alt="">
              <!-- image -->
              <img @click="imgPreview(scope.row[props.prop])"
                   :style="{width:props.width,height:props.height}"
                   v-if="props.type == 'image'"
                   :src="scope.row[props.prop]"
                   alt="">
              <!-- 状态 -->
              <span v-if="props.type == 'status'">{{scope.row[props.prop] == props.active_val ? '是' : '否'}}</span>
              <!-- input -->
              <el-input v-if="props.type == 'input'"
                        v-model="scope.row[props.prop]"
                        @blur="blurHandler(scope.row,props.url)"></el-input>
              <!-- 开关 -->
              <el-switch @change="switchHandler(scope.row,props.prop,props.url)"
                         v-if="props.type == 'switch'"
                         active-value="1"
                         inactive-value="0"
                         v-model="scope.row[props.prop]">
              </el-switch>
            </template>
          </el-table-column>
        </template>

      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="pagination" v-if="is_show_pagination">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="current_page"
                     :page-sizes="pageSizes"
                     :layout="layout"
                     :total="total"
                     v-bind="{...paginationConfig}"></el-pagination>
    </div>
    <!-- 预览图片 -->
    <el-dialog title="预览"
               :visible.sync="is_preview"
               :modal="false">
      <img :src="preview_url"
           alt="">
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog class="table_dialog"
               title="详情"
               :visible.sync="is_detail"
               :modal="false"
               :width="detail_width">
               <slot name="detail_content" :data="detail_info"></slot>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog class="table_dialog"
               title="编辑"
               v-if="is_edit"
               :visible.sync="is_edit"
               :modal="false"
               width="50%">
      <Form ref="form"
            :formData="editData"
            @submit="submitEdit"
            @reset="reset"
            :labelWidth="labelWidth"
            :showReset="false"
            :inline="true"></Form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      is_edit: false,
      is_preview: false,
      is_detail:false,
      detail_info:'',
      preview_url: ''
    };
  },
  props: {
    // 表格配置
    tableConfig: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 表单标题宽度
    labelWidth: {
      type: String,
      default: () => {
        return "100px";
      }
    },
    // 是否显示分页器
    is_show_pagination:{
      type: Boolean,
      default: () => {
        return true;
      }
    },
    // 分页器配置
    paginationConfig: {
      type: Object
    },
    // 分页器下拉选择页数
    pageSizes: {
      type: Array,
      default: () => {
        return [10, 20];
      }
    },
    // 分页器样式
    layout: {
      type: String,
      default: () => {
        return "sizes,total, prev, pager, next,jumper";
      }
    },
    // 横列数据
    tableData: {
      type: Array,
      required: true
    },
    // 纵列数据
    columnData: {
      type: Array,
      required: true
    },
    // 总条数
    total: {
      type: Number,
      required: true
    },
    // 表格类型
    // selection/index/expand
    column_type: {
      type: String,
      default: () => {
        return 'index'
      }
    },
    // 当前页码
    current_page: {
      type: Number,
      default: () => {
        return 1
      }
    },
    // 编辑表单
    editData: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 编辑链接
    edit_url: {
      type: String
    },
    // 详情链接
    detail_url: {
      type: String
    },
    // 详情弹窗大小
    detail_width:{
      type: String,
      default:() => {
        return '50%'
      }
    },
    // 编辑表单是否使用默认的选项
    is_default_edit: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  methods: {
    resetPage () {
      this.current_page = 1;
    },
    // 预览图片
    imgPreview (url) {
      this.is_preview = true;
      this.preview_url = url;
    },
    // 切换条数时触发
    handleSizeChange (val) {
      this.$emit("handleSizeChange", val);
    },
    // 切换页码时触发
    handleCurrentChange (val) {
      this.$emit("handleCurrentChange", val);
    },
    handleSelectionChange (val) {
      this.$emit("handleSelectionChange", val);
    },
    // 清空多选表格
    clearSelection () {
      this.$refs.table.clearSelection();
    },
    // 处理按钮点击事件
    btnHandler (row, item) {
      switch (item.type) {
        // 查看详情
        case 'detail':
          var loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.4)'
          });
          setTimeout(() => {
            loading.close();
          }, 2000);
          this.$req.get(item.url,{...row}).then(res =>{
            this.is_detail = true;
            this.detail_info = res.data;
            loading.close();
          })
          break;
        // 编辑表格
        case 'edit':
          var loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.4)'
          });
          setTimeout(() => {
            loading.close();
          }, 2000);

          this.editData.forEach(item => {
            item.value = '';
            if (!this.is_default_edit) {
              if ('groups' in item) {
                item.groups = []
              }
            }

            if ('config' in item && 'fileList' in item.config) {
              item.config.fileList = []
            }
          })
          this.editData.forEach((item, idx) => {
            if ('url_rule' in item) {
              let req = row[item.url_rule.rule] == '0' ? this.$req.get(item.url_rule.url[0]) : this.$req.get(item.url_rule.url[1])
              req.then(res => {
                let data = res.data;
                for (var i in data) {
                  console.log(item)
                  item.groups.push({
                    label: data[i][item.url_rule.labelKey],
                    value: data[i][item.url_rule.valueKey]
                  })
                }
                if (item.url_rule.rule == 'isfree') {
                  item.value = item.category_name == '免费礼劵' ? item.groups[0].value : item.groups[1].value
                }
              })
            }
          })
          let data = {}
          data[item.detail_mark] = row[item.detail_mark];
          this.$req.get(this.detail_url, data).then(res => {
            let data = res.data;
            this.editData.forEach((item, idx) => {
              Object.keys(data).forEach((item2) => {
                if (item.name == item2) {
                  this.$set(this.editData[idx], 'value', data[item2])
                  // 处理选择框赋值
                  if ('sel_rule' in item) {
                    let rule = item.sel_rule;
                    let sr = item.sel_arr;
                    let show_arr = []
                    let count = 0;
                    for (let i in rule) {
                      if (rule[i].id == data[item2]) {
                        show_arr = rule[i].show_arr;
                        count = 1;
                        console.log(rule[i])
                        if ('change_arr' in rule[i]) {
                          this.selHandler(rule[i].change_arr);
                        }
                      }
                    }

                    let fd = this.editData;
                    for (let i in fd) {
                      for (let j in sr) {
                        if (fd[i].name == sr[j]) {
                          fd[i].display = 'none';
                        }
                      }
                    }
                    for (let i in fd) {
                      for (let j in show_arr) {
                        if (fd[i].name == show_arr[j]) {
                          fd[i].display = true;
                        }
                      }
                    }

                  }
                  // 处理图片赋值
                  if (item.type == 'image_upload') {
                    console.log(item);
                    if (Array.isArray(data[item2])) {
                      data[item2].forEach((item3, idx) => {
                        console.log(item3)
                        item.config.fileList.push({
                          name: `image${idx}`,
                          url: item3
                        })
                      })
                    } else {
                      item.config.fileList.push({
                        name: `image1`,
                        url: data[item2]
                      });
                    }
                  }
                }
              })
            })
            this.is_edit = true;
            loading.close()
          })
          break;
        // 删除表格
        case 'delete':
          this.$confirm('是否删除').then(() => {
            row.display = '9'
            this.editHandler(row, item.url, true).then(res => {
              this.$emit('refresh')
              this.$msg({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
            })
          })
          break;
      }
    },
    selHandler (change_arr) {
      let fd = this.editData;
      for (var i in change_arr) {
        this.$req.get(change_arr[i].url).then(res => {
          let data = res.data;
          for (var j in fd) {
            if (fd[j].name == change_arr[i].name) {
              fd[j].groups = [];
              for (var k in data) {
                fd[j].groups.push({
                  label: data[k][change_arr[i].labelKey],
                  value: data[k][change_arr[i].valueKey]
                })
              }
            }
          }
        })
      }
    },
    // 提交编辑
    submitEdit (e) {
      console.log(e)
      this.$req.post(this.edit_url, e.data).then(res => {
        this.$msg({
          showClose: true,
          message: '编辑成功',
          type: 'success'
        })
        this.is_edit = false;
        this.$emit('refresh')
      })
    },
    // 清空编辑
    reset (e) {
      this.$emit('resetEdit', e)
    },
    // 处理输入框失焦事件
    blurHandler (row, url) {
      console.log(row);
      console.log(url);
      this.editHandler(row, url)
    },
    // 开关处理事件
    switchHandler (row, name, url) {
      console.log(row);
      console.log(name);
      console.log(url);
      this.editHandler(row, url);
    },
    // 执行修改事件
    editHandler (row, url, bool = false) {
      return new Promise((resolve, reject) => {
        this.$req.post(url, { ...row }).then(res => {
          if (!bool) {
            this.$msg({
              showClose: true,
              message: res.msg,
              type: 'success'
            })
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
  }
};
</script>
<style lang='scss' scoped>
.table_content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #ebebeb;
  padding: 20px;
  // max-width: 1200px;
  // margin: 0 auto;
  .table_icon {
    width: 40px;
    height: 40px;
  }
  .is_btn_group {
    min-width: 200px;
  }
  .pagination {
    margin-top: 20px;
  }
}
/deep/.el-dialog {
  max-height: 700px;
  overflow: hidden;
  overflow-y: auto;
  overflow-x: auto;
}
.table_dialog {
}
/deep/.el-dialog__wrapper {
  z-index: 999 !important;
}
</style>